package com.hl.modules_main.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.hl.base_module.adapter.BaseMutilayoutAdapter;
import com.hl.base_module.constant.ArouterPath;
import com.hl.base_module.message.MessageEvent;
import com.hl.base_module.page.BaseWithServiceFragment;
import com.hl.base_module.util.rv.RecycleViewDivider;
import com.hl.base_module.util.screen.ScreenUtil;
import com.hl.base_module.viewmodel.SelfViewModelFactory;
import com.hl.lib_refreshlayout.handler.RefreshListenner;
import com.hl.lib_webview.view.WebviewActivity;
import com.hl.modules_main.R;
import com.hl.modules_main.databinding.FragmentHomeBinding;
import com.hl.modules_main.model.bean.HomeBean;
import com.hl.modules_main.view.adapter.HomeAdatper;
import com.hl.modules_main.view.event.HomeEventHandler;
import com.hl.modules_main.viewmodel.HomeViewModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
@Route(path = ArouterPath.HOME_FRAGMENT)
public class HomeFragment extends BaseWithServiceFragment<FragmentHomeBinding> {
    // 碎片databinding一把
    private FragmentHomeBinding fragmentHomeBinding;
    private HomeAdatper homeAdatper;
    private int current_page = 0;
    private List<HomeBean.DatasBean> rvBeanList = new ArrayList<>();

    public HomeViewModel homeViewModel;
    private HomeEventHandler homeEventHandler;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment PersonalFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int setLayout() {
        return R.layout.fragment_home;
    }

    @Override
    public void initLayout(Context context) {
        EventBus.getDefault().register(this);

        fragmentHomeBinding = getViewDataBinding();
        // 设置banner距离顶部高度
        ScreenUtil.setStatusBarHeightTop(fragmentHomeBinding.fhBvp2);

        // 初始化列表
        homeAdatper = new HomeAdatper(requireContext(), rvBeanList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireContext());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        fragmentHomeBinding.fhHomeListRv.addItemDecoration(new RecycleViewDivider(
                context,
                LinearLayoutManager.VERTICAL,
                3, R.color.little_gray));
        fragmentHomeBinding.fhHomeListRv.setLayoutManager(linearLayoutManager);
        fragmentHomeBinding.fhHomeListRv.setAdapter(homeAdatper);
        // 默认先隐藏banner组件，等请求成功后再显示
        fragmentHomeBinding.fhBvp2.setVisibility(View.GONE);
    }

    @Override
    public void requestData(Context context) {
        // 自定义ModelFactory创建ViewModel
        homeViewModel = new ViewModelProvider(this, new SelfViewModelFactory(baseControlPresenter)).get(HomeViewModel.class);
        // 监听列表数据变化
        homeViewModel.getHomeLd().observe(this, new Observer<List<HomeBean.DatasBean>>() {
            @Override
            public void onChanged(List<HomeBean.DatasBean> datasBean) {
                // 请求成功再显示banner
                fragmentHomeBinding.fhBvp2.setVisibility(View.VISIBLE);

                // 添加一个Banner
                List<String> imgList = new ArrayList<>();
                imgList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1588156088710&di=055003d07ddf9187b8cc2aaf1b13f9f0&imgtype=0&src=http%3A%2F%2Fattach.bbs.miui.com%2Fforum%2F201012%2F18%2F11241689kkepeiyerc77es.jpg");
                imgList.add("https://gitee.com/heyclock/mvvm_modularization/raw/master/zdoc/pic/mvvm.jpg");
                imgList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1588156186767&di=95bb7b55315bd75a49e2fda30a82a204&imgtype=0&src=http%3A%2F%2Fattachments.gfan.com%2Fforum%2F201411%2F07%2F1056118jxbvrblfrc2c72x.gif");
                fragmentHomeBinding.fhBvp2
                        .setData(imgList)
                        .start(1.5f);

                if (0 == current_page) {
                    fragmentHomeBinding.fhHomeListHR.finishRefresh(0);
                    rvBeanList.clear();
                    rvBeanList.addAll(datasBean);
                    homeAdatper.notifyDataSetChanged();
                } else {
                    fragmentHomeBinding.fhHomeListHR.finishLoadMore(0);
                    rvBeanList.addAll(datasBean);
                    homeAdatper.notifyDataSetChanged();
                }
            }
        });
        // 请求首页数据
        homeEventHandler.getHomeListData((current_page = 0));
    }

    @Override
    public void eventHandler(Context context) {
        // 注册事件对象
        if (null == fragmentHomeBinding.getClickHandler()) {
            fragmentHomeBinding.setClickHandler(homeEventHandler = new HomeEventHandler(this));
        }
        fragmentHomeBinding.fhHomeListHR.setOnRefreshListenner(new RefreshListenner() {
            @Override
            public void OnRefresh() {
                homeEventHandler.getHomeListData((current_page = 0));
            }

            @Override
            public void OnRefreshFinish() {
                EventBus.getDefault().post(new MessageEvent("刷新失败, 结束", "update_home_finish"));
            }

            @Override
            public void OnLoadMore() {
                homeEventHandler.getHomeListData(++current_page);
            }

            @Override
            public void OnLoadMoreFinish() {
            }
        });
        // 点击跳转到浏览器页面
        homeAdatper.setOnItemClickListener(new BaseMutilayoutAdapter.OnItemClickListener<HomeBean.DatasBean>() {
            @Override
            public void onClick(View v, int position, HomeBean.DatasBean datasBean, int itemViewType, Object externParams) {
                Bundle bundle = new Bundle();
                bundle.putString("html", datasBean.getLink());
                Intent intent = new Intent(requireContext(), WebviewActivity.class);
                intent.putExtras(bundle);
                requireContext().startActivity(intent);
            }
        });
    }

    /**
     * 收到刷新
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void studentEventBus(MessageEvent messageEvent) {
        if (messageEvent.getObject().equals("update_home")) {
            fragmentHomeBinding.fhHomeListHR.autoRefresh();
        }
    }

    @Override
    public void onSucess(String _functionName, Object t) {
        if (t instanceof HomeBean) {
            HomeBean homeBean = (HomeBean) t;
            homeViewModel.getHomeLd().setValue(homeBean.getDatas());
        }
    }

    @Override
    public void onFailed(String _functionName, String _message) {
        if (0 == current_page) {
            fragmentHomeBinding.fhHomeListHR.finishRefresh(0);
        } else {
            fragmentHomeBinding.fhHomeListHR.finishLoadMore(0);
        }
    }
}
